import { message } from 'antd';
// @ts-ignore
import { Effect, history, Reducer } from 'umi';
// @ts-ignore
import request from '@/utils/request';

export interface StateType {
  status?: 'ok' | 'error';
  type?: undefined | 'ssosdfasefasdef' | 'normal';
  browserList: any;
  copyright: any;
  userInfo: any;
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  subscriptions: any;
  effects: {
    login: Effect;
    logout: Effect;
    register: Effect;
  };
  reducers: {
    setState: Reducer;
  };
}

// eslint-disable-next-line no-promise-executor-return
const delay = (time: any) =>
  new Promise((resolve) => setTimeout(resolve, time || 0));
const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
    type: undefined,
    browserList: [],
    copyright: {},
    userInfo: {},
  },
  subscriptions: {},
  effects: {
    *login({ payload }: any, { call, put }: any) {
      // @ts-ignore
      const data: any = yield call(() =>
        request('/api2/auth/login', {
          method: 'post',
          data: { userName: payload?.username, passWord: payload?.password },
          headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
          },
        }),
      );
      if (data.code && data.code === 200) {
        message.success('登录成功');
        sessionStorage.setItem('token', data.data.token);
        sessionStorage.setItem('access', JSON.stringify(data.data.access));
        sessionStorage.setItem('userInfo', JSON.stringify(data.data.userInfo));
        yield delay(500);
        setTimeout(() => (window.location.href = '/'), 500); // 解决跳转之后权限菜单没有立马更新问题
        // console.log('延迟了')
      } else {
        message.error(data.msg || '登录失败');
      }
    },
    *logout() {
      // const sso = sessionStorage.getItem('sso');
      // @ts-ignore
      // const success: any = yield call(() =>
      //     request.post('api/logout', {data: {}}),
      // );
      // if (success) {
      //     sessionStorage.removeItem('userInfo');
      //     history.push('/login');
      //     yield put({type: 'upState', payload: {userInfo: {}}});
      //     message.success('已安全退出!');
      // }
    },
    *register({ payload }: any, { call }: any) {
      // @ts-ignore
      const data: any = yield call(() =>
        request('/api2/auth/register', {
          method: 'post',
          data: {
            userName: payload?.username,
            nickName: payload?.nickName,
            // passWord: payload?.password,
            passWord: '1qaz!QAZ',
          },
        }),
      );
      if (data.code && data.code === 200) {
        message.success('注册成功');
        setTimeout(() => history.push('/login'), 500);
      } else {
        message.warning(data.msg);
      }
    },
  },

  reducers: {
    setState(state: any, { payload }: any) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default Model;
